﻿using FlexFlow.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FlexFlow.Runtime
{
    /// <summary>
    /// 为管理器提供基类
    /// </summary>
    public abstract class ManagerBase
    {
        /// <summary>
        /// 该管理器使用的组件集合
        /// </summary>
        internal protected ComponentSettings Components { get; private set; }
        /// <summary>
        /// 设置信息项
        /// </summary>
        /// <param name="dictionary">
        /// 信息项目录
        /// </param>
        /// <param name="key">
        /// 信息项键
        /// </param>
        /// <param name="value">
        /// 信息项值
        /// </param>
        /// <returns>
        /// 一个值，表示设置是否成功
        /// </returns>
        protected bool SetInformation(string dictionary, string key, string value)
        {
            WorkFlowInformation info = this.Components.WorkFlowInformationProvider.Get(dictionary, key);
            if (info == null)
            {
                info = this.Components.WorkFlowInformationProvider.Create();
                info.Directory = dictionary;
                info.Key = key;
                info.Value = value;
                return this.Components.WorkFlowInformationProvider.Add(info);
            }
            return this.Components.WorkFlowInformationProvider.SetValue(info.Identity, value);
        }
        /// <summary>
        /// 取得信息项的值
        /// </summary>
        /// <param name="dictionary">
        /// 信息项的目录
        /// </param>
        /// <param name="key">
        /// 信息项的键
        /// </param>
        /// <param name="defaultVal">
        /// 信息项的默认值
        /// </param>
        /// <param name="createIfNotExist">
        /// 一个标记值，该值指示当信息不存在时是否创建信息
        /// </param>
        /// <returns>
        /// 信息项的值，如果设定项不存在并且新建信息项不成功则返回null
        /// </returns>
        protected string GetInformation(string dictionary, string key, string defaultVal, bool createIfNotExist = true)
        {
            WorkFlowInformation info = this.Components.WorkFlowInformationProvider.Get(dictionary, key);
            if (info == null)
            {
                if (!createIfNotExist)
                {
                    return defaultVal;
                }
                if (SetInformation(dictionary, key, defaultVal))
                {
                    return defaultVal;
                }
                return null;
            }
            return info.Value;
        }

        public ManagerBase()
        {
            this.Components = new ComponentSettings();
        }
    }
}
